package fun.formoji.commons.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <code>FeignInterceptor</code>
 * <desc>
 * 描述： feign调用其他服务会丢失Token的请求头
 * REMARK FEIGN传递请求头获取时候自动把首字母小写了..
 * <desc/>
 * Creation Time: 2020/3/25 0:37.
 *
 * @author hshe
 */
// @Configuration
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
    private static final String HEADER_REQUEST_ID = "x-request-id";

    @Override
    public void apply(RequestTemplate template) {
        Map<String, String> headers;
        try {
            headers = getHeaders(getHttpServletRequest());
        } catch (Exception e) {
            log.error("Feign服务传递请求头失败", e);
            return;
        }
        String requestId = headers.get(HEADER_REQUEST_ID);
        template.header(HEADER_REQUEST_ID, requestId);
        MDC.put(HEADER_REQUEST_ID, requestId);
    }

    private HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
